package com.vsu.bookstore.mvc.ui.window;

import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;

import org.apache.commons.mail.EmailException;
import org.vaadin.henrik.superimmediatetextfield.SuperImmediateTextField;
import org.vaadin.henrik.superimmediatetextfield.SuperImmediateTextField.KeyPressEvent;
import org.vaadin.henrik.superimmediatetextfield.SuperImmediateTextField.KeyPressListener;

import com.vaadin.data.Validator;
import com.vaadin.data.validator.RegexpValidator;
import com.vaadin.ui.Button;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;
import com.vaadin.ui.Button.ClickEvent;
import com.vsu.bookstore.BookstoreApplication;
import com.vsu.bookstore.mvc.ui.widgets.CancelButton;
import com.vsu.bookstore.mvc.ui.widgets.CheckoutTable;
import com.vsu.bookstore.mvc.ui.widgets.OkButton;
import com.vsu.bookstore.util.EmailUtils;
import com.vsu.bookstore.util.UserSession;

@SuppressWarnings("serial")
public class CheckoutWindow extends Window
{
  private CheckoutTable table = null;

  private final Button submitButton = new OkButton();

  private final Button cancelButton = new CancelButton();

  private final SuperImmediateTextField emailField = new SuperImmediateTextField("Enter your email: ");

  public CheckoutWindow(final UserSession session)
  {
    super();
    setCaption("Checkout");
    final String emailRegExp = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
    emailField.addValidator(new RegexpValidator(emailRegExp, "Invalid e-mail"));
    emailField.setImmediate(true);
    emailField.setRequiredError("U have to enter your mail - it is required!!!");

    emailField.addListener(new KeyPressListener()
    {
      public void keyPressed(final KeyPressEvent event)
      {
        final Collection<Validator> validators = emailField.getValidators();
        final Iterator<Validator> it = validators.iterator();
        while (it.hasNext())
        {
          final Validator validator = it.next();
          if (validator instanceof RegexpValidator)
          {
            submitButton.setEnabled(validator.isValid(emailField.getValue()));
            break;
          }
        }
      }
    });
    emailField.setWidth("100%");
    table = new CheckoutTable(session.getCartContainer());
    final VerticalLayout layout = new VerticalLayout();
    setContent(layout);
    layout.setWidth("700px");
    layout.setMargin(true);
    layout.setSpacing(true);
    layout.addComponent(table);
    layout.addComponent(emailField);
    layout.addComponent(populateFooter());
    layout.setExpandRatio(table, 1.0f);
    setClosable(false);
    setResizable(false);
    setModal(true);
    setDraggable(false);
    center();
    submitButton.setEnabled(false);
    submitButton.addListener(new Button.ClickListener()
    {
      public void buttonClick(final ClickEvent event)
      {
        final BookstoreApplication app = (BookstoreApplication)getApplication();
        final Window mainWnd = app.getMainWindow();
        sendConfirmation();
        mainWnd.removeWindow(CheckoutWindow.this);
        mainWnd.showNotification("Thank You So Much For Buying Those Fancy Items From Our BookStore, Bro!", Notification.TYPE_WARNING_MESSAGE);
        app.ui().clearCartPanel();
        app.getSession().clear();
      }
    });

    cancelButton.addListener(new Button.ClickListener()
    {
      public void buttonClick(final ClickEvent event)
      {
        getApplication().getMainWindow().removeWindow(CheckoutWindow.this);
      }
    });
  }

  public void beforeShow()
  {
    table.updatePriceFooter();
  }

  private HorizontalLayout populateFooter()
  {
    final HorizontalLayout result = new HorizontalLayout();
    result.setSizeUndefined();
    result.addComponent(submitButton);
    result.addComponent(cancelButton);
    return result;
  }

  private void sendConfirmation()
  {
    final String purchaseMsg = ((BookstoreApplication)getApplication()).getSession().getPurchaseMessage();
    try
    {
      EmailUtils.sendEmail(emailField.getValue().toString(), purchaseMsg);
    }
    catch (final EmailException e)
    {
      e.printStackTrace();
    }
    catch (final IOException e)
    {
      e.printStackTrace();
    }
  }

}
